#!/user/bin/env python
# -*- coding: utf-8 -*-

from utils import log

from sqlalchemy.orm import mapper, sessionmaker
from sqlalchemy import Table, MetaData, Column, Integer, String, Unicode, UnicodeText, DateTime
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

""" topic_note_img collection has
    id:             自增id（int）
    topic:          话题id（int）
    noteid:         内容id（int）
    imgid:          图片id（string）
    #imgseq:         图片在note中的次序（int）
    ctime:          添加时间（datetime）
"""


class TopicNoteImgItem(object):
    """docstring for TopicNoteImgItem"""

    def to_dict(self):
        res = {}
        res['topicid'] = self.topicid
        res['noteid'] = self.noteid
        if not self.imgid:
            res['imgid'] = []
        else:
            res['imgid'] = [int(item) for item in self.imgid.split(',')]
        #res['imgseq'] = self.imgseq
        res['ctime'] = self.ctime
        return res

    def __repr__(self):
        return "%d" % (self.imgid)

topic_note_img_table = Table(
    'topic_note_img', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('topicid', Integer, index=True, nullable=True),
    Column('noteid', Integer, index=True, nullable=True),
    Column('imgid', UnicodeText, nullable=True),
    #Column('imgseq', Integer, nullable=True, default=1),
    Column('ctime', TIMESTAMP, server_default=func.now()),
)

mapper(TopicNoteImgItem, topic_note_img_table)


def create_topic_note_img_table_if_not_exist():
    metadata.create_all(engine)


def add_topic_note_img_item(p_item):
    """

    :param p_item:
        imgid 是列表类型
    :return:
    """
    item = TopicNoteImgItem()
    item.topicid = p_item['topicid']
    item.noteid = p_item['noteid']
    item.imgid = ','.join([str(i) for i in p_item['imgid']])
    #item.imgseq = p_item['imgseq']

    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_topic_note_img_by_noteid_list(p_noteid_list):
    try:
        session = Session()
        items = session.query(TopicNoteImgItem)\
            .filter(TopicNoteImgItem.noteid.in_(p_noteid_list)).all()
        res_list = [item.to_dict() for item in items]
        return res_list

    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()

def get_topic_note_img_map_by_noteid_list(p_noteid_list):
    try:
        session = Session()
        items = session.query(TopicNoteImgItem)\
            .filter(TopicNoteImgItem.noteid.in_(p_noteid_list)).all()

        note_img_dict_map = {}
        note_img_map = {}
        for item in items:
            if item.noteid not in note_img_dict_map:
                note_img_dict_map[item.noteid] = {}
            note_img_dict_map[item.noteid][item.imgseq] = item.imglink
        for noteid in note_img_dict_map:
            tmp_dict = note_img_dict_map[noteid]
            note_img_map[noteid] = [tmp_dict[key]
                                    for key in sorted(tmp_dict)]
        return note_img_map
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_topic_note_img_by_topicid(p_topicid):
    try:
        session = Session()
        item_list = session.query(TopicNoteImgItem) \
            .filter_by(topic=p_topicid).all()
        res = [item.to_dict() for item in item_list]
        return res
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def get_topic_note_img_by_noteid(p_noteid):
    try:
        session = Session()
        item = session.query(TopicNoteImgItem) \
            .filter_by(noteid=p_noteid).first()
        if item:
            return item.to_dict()
        return None
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


def delete_topic_note_img_by_noteid(p_noteid):
    try:
        session = Session()
        session.query(TopicNoteImgItem).filter_by(noteid=p_noteid).delete()
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def update_topic_note_img_by_noteid(p_noteid, p_note_img_item):
    try:
        session = Session()
        session.query(TopicNoteImgItem).filter_by(noteid=p_noteid).update(p_note_img_item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()


if __name__ == "__main__":
    create_topic_note_img_table_if_not_exist()
    item = {
        'topicid': 1,
        'noteid': 1,
        'imgid': ['1, 2, 3, 4'],
        #'imgseq': 1
    }
    add_topic_note_img_item(item)
